using System;
using System.Collections.Generic;
using System.Text;
using IronPython.Hosting;
using System.IO;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;


namespace InitEngineDemo
{
    class Program
    {

        private static ScriptEngine debuggableEngine;


        static void Main(string[] args)
        {
            String[] raise = new string[] 
                {"x = 1", "class C(object):", 
                "    def __init__(self):",
                "        self.attr = 1",
                "        raise \"Exception from py\"",
                "c = C()", 

                "# The following statement should not be executed.",
                "y = 1"};
            File.WriteAllLines("raise.py", raise);

            // Execute the script using different property values.

            RunScript(true, true, true);
            RunScript(true, true, false);
            //RunScript(true, false, true);
            RunScript(true, false, false);
            //RunScript(false, true, false);
            //RunScript(false, false, true);
            RunScript(false, true, false);

            Console.Read();

        }
        private static void RunScript(bool enabled, bool show, bool detail)
        {
            try
            {
                Console.WriteLine("\nClrDebuggingEnabled = {0}, ShowClrExceptions = {1}, ExceptionDetail = {2}\n", enabled, show, detail);

                debuggableEngine = PythonEngine.CurrentEngine;
          
                /// Whether the application is in debug mode.
                /// This means:
                /// 
                /// 1) Symbols are emitted for debuggable methods (methods associated with SourceUnit).
                /// 2) Debuggable methods are emitted to non-collectable types (this is due to CLR limitations on dynamic method debugging).
                /// 3) Dynamic stack frames of debuggable methods are recorded at run-time 
                /// 4) JIT optimization is disabled for all methods
                /// 5) Languages may disable optimizations based on this value.
                debuggableEngine.Runtime.GlobalOptions.DebugMode = enabled;
                debuggableEngine.Options.ShowClrExceptions = show;
                debuggableEngine.Options.ExceptionDetail = detail;
                ScriptScope scope = debuggableEngine.Runtime.CreateScope();
                debuggableEngine.CreateScriptSourceFromFile("raise.py").Execute(scope);
            }
            catch (IronPython.Runtime.Exceptions.StringException e1)
            {
                //Format the exception for display to the console.
                Console.Write(debuggableEngine.FormatException(e1));

            }
        }

    }
}
